home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9144 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.lpr.carel.fi!usenet
  2. From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: read/write integers to files
  5. Date: Thu, 07 Mar 1996 16:48:28 +0200
  6. Organization: Carelcomp Forest
  7. Message-ID: <313EF73C.3B54@cmt.lpr.mail.carel.fi>
  8. References: <313EBF65.4E82@www.inia.net.au>
  9. NNTP-Posting-Host: renoir.cclahti.carel.fi
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (WinNT; I)
  14.  
  15. Jason Collins wrote:
  16. > Hi there,
  17. > I would preface this question with the standard "dumb newbie question......." or whatever but I
  18. > think you'll work it out for yourselves soon enough.
  19. > My problem is that I'm trying to write a program that will read an integer from the file
  20. > count.dat, increment the integer then write it back to count.dat.  I have provided the listing so
  21. > that you can all tell me what I'm doing wrong.
  22. > Thanks....and.....be gentle.
  23. > --------------------
  24. > counter.c
  25. > --------------------
  26. > #include <stdio.h>
  27. > #include <stdlib.h>
  28. > FILE *filePtr;
  29. > void main()
  30. > {
  31. >   char ctr;
  32. >   filePtr=fopen("count.dat", "ab");
  33. >   fscanf(filePtr, "%d", &ctr);
  34. >   fclose(filePtr);
  35. >   ctr++;
  36. >   filePtr=fopen("count.dat", "wb");
  37. >   fprintf(filePtr, "%d", ctr);
  38. >   fclose(filePtr);
  39. > }
  40.  
  41. Reading an integer? Why not declare it so, then:
  42.  
  43.     int    ctr;
  44.  
  45. And, if you don't plan to append data to the end of the file, why open it in append 
  46. mode? You could use just "rb" instead.
  47.  
  48. The second fopen in "wb" mode still will truncate the file to zero-length if it 
  49. exists. You could try "rb+" (open in read binary mode with ability to write also):
  50.  
  51.     filePtr = fopen("count.dat", "rb+");
  52.     fscanf(filePtr, "%d", &ctr);
  53.     ctr++;
  54.     rewind(filePtr);
  55.     fprintf(filePtr, "%d", ctr);
  56.     fclose(filePtr);
  57.  
  58. However, I'd stick Xscanf to where it belongs and use fread/fwrite instead, when 
  59. dealing with binary data. Fseek is also an useful function.
  60.  
  61. Also, checking for failures in fopen etc is a good programming practice.
  62.  
  63. Later,
  64.  AriL
  65. -- 
  66. All my opinions are mine and mine alone.
  67.